using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using Sample.Novel.EntityFrameworkCore;
using Sample.Novel.TestBase;
using System;
using Volo.Abp;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Sqlite;
using Volo.Abp.Modularity;
using Xunit;

namespace Sample.Novel.EntityFramework.Tests
{
    [DependsOn(typeof(AbpEntityFrameworkCoreSqliteModule),
        typeof(NovelTestBaseModule),
        typeof(NovelEntityFrameworkModule)
        )]
    public class NovelEntityFrameworkCoreTestModule
        :AbpModule
    {
        private SqliteConnection _sqliteConneion;
        private static SqliteConnection CreateDatabaseAndGetConnectoin() {
            var connection = new SqliteConnection("Data Source=:memory:");
            connection.Open();
            var options = new DbContextOptionsBuilder<NovelDbContext>()
                .UseSqlite(connection)
                .Options;
            using var context = new NovelDbContext(options); ;
            context.GetService<IRelationalDatabaseCreator>().CreateTables();
            return connection;
        }

        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            _sqliteConneion = CreateDatabaseAndGetConnectoin();
            context.Services.Configure<AbpDbContextOptions>(options => {
                options.Configure(configurationContext =>
                    configurationContext.DbContextOptions.UseSqlite(_sqliteConneion)
                );
            });
        }

        public override void OnApplicationShutdown(ApplicationShutdownContext context)
        {
            _sqliteConneion.Dispose();
        }
    }
}
